package com.lostreseditores.sabersai.model.control;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.lostreseditores.sabersai.dataaccess.daoFactory.XMLHibernateDaoFactory;
import com.lostreseditores.sabersai.dataaccess.sessionFactory.HibernateSessionFactory;
import com.lostreseditores.sabersai.exceptions.ZMessManager;
import com.lostreseditores.sabersai.model.Calificacion;
import com.lostreseditores.sabersai.model.Colegio;
import com.lostreseditores.sabersai.model.dto.ColegioDTO;
import com.lostreseditores.sabersai.utilities.Utilities;


public class ColegioLogic implements IColegioLogic {
	public List<Colegio> getColegio() throws Exception {
		List<Colegio> list = new ArrayList<Colegio>();

		try {
			list = XMLHibernateDaoFactory.getInstance().getColegioDAO()
					.findAll();
		} catch (Exception e) {
			throw new ZMessManager().new GettingException(ZMessManager.ALL
					+ "Colegio");
		} finally {
		}

		return list;
	}

	public void saveColegio(Long colecoddanen, String coledescripv,
			 Long lugaidn) throws Exception {
		
		List<Colegio> entity = null;
		Colegio cole = null;

		try {
			if ((colecoddanen != null)
					&& (Utilities.checkNumberAndCheckWithPrecisionAndScale(""
							+ colecoddanen, 131089, 0) == false)) {
				throw new ZMessManager().new NotValidFormatException(
						"colecoddanen");
			}

			if ((coledescripv != null)
					&& (Utilities
							.checkWordAndCheckWithlength(coledescripv, 150) == false)) {
				throw new ZMessManager().new NotValidFormatException(
						"coledescripv");
			}
			
			/*if (coleidn == null) {
				throw new ZMessManager().new EmptyFieldException("coleidn");
			}*/

			entity = getColegioDane(colecoddanen);

			if (entity.size()!=0) {
				throw new ZMessManager(ZMessManager.ENTITY_WITHSAMEKEY);
			}

			cole = new Colegio();
			cole.setColecoddanen(colecoddanen);
			cole.setColedescripv(coledescripv);
			cole.setLugaidn(lugaidn);
			HibernateSessionFactory.beginTransaction();
			XMLHibernateDaoFactory.getInstance().getColegioDAO().save(cole);
			HibernateSessionFactory.commit();
		} catch (Exception e) {
			HibernateSessionFactory.rollback();
			throw e;
		} finally {
			HibernateSessionFactory.closeSession();
		}
	}

	public void deleteColegio(Integer coleidn) throws Exception {
		Colegio entity = null;

		if (coleidn == null) {
			throw new ZMessManager().new EmptyFieldException("coleidn");
		}

		List<Calificacion> calificacions = null;
		entity = getColegio(coleidn);

		if (entity == null) {
			throw new ZMessManager().new EmptyFieldException("Colegio");
		}

		try {
			calificacions = XMLHibernateDaoFactory.getInstance()
					.getCalificacionDAO()
					.findByProperty("colegio.coleidn", coleidn);

			if (Utilities.validationsList(calificacions) == true) {
				throw new ZMessManager().new DeletingException("calificacions");
			}

			HibernateSessionFactory.beginTransaction();
			XMLHibernateDaoFactory.getInstance().getColegioDAO().delete(entity);
			HibernateSessionFactory.commit();
		} catch (Exception e) {
			HibernateSessionFactory.rollback();
			throw e;
		} finally {
			HibernateSessionFactory.closeSession();
		}
	}

	public void updateColegio(Integer coleidn, Long colecoddanen, String coledescripv, Long lugaidn) throws Exception {
		Colegio cole = null;

		try {
			if ((colecoddanen != null)
					&& (Utilities.checkNumberAndCheckWithPrecisionAndScale(""
							+ colecoddanen, 131089, 0) == false)) {
				throw new ZMessManager().new NotValidFormatException(
						"colecoddanen");
			}

			if ((coledescripv != null)
					&& (Utilities
							.checkWordAndCheckWithlength(coledescripv, 150) == false)) {
				throw new ZMessManager().new NotValidFormatException(
						"coledescripv");
			}

		if ((lugaidn != null)
					&& (Utilities.checkNumberAndCheckWithPrecisionAndScale(""
							+ lugaidn, 131089, 0) == false)) {
				throw new ZMessManager().new NotValidFormatException("lugaidn");
			}

			/*
			 * if (entity.size()!=0) { throw new
			 * ZMessManager(ZMessManager.ENTITY_WITHSAMEKEY); }
			 */
			cole = new Colegio();
			cole.setColeidn(coleidn);
			cole.setColecoddanen(colecoddanen);
			cole.setColedescripv(coledescripv);
			cole.setLugaidn(lugaidn);
			HibernateSessionFactory.beginTransaction();
			XMLHibernateDaoFactory.getInstance().getColegioDAO().update(cole);
			HibernateSessionFactory.commit();
		} catch (Exception e) {
			HibernateSessionFactory.rollback();
			throw e;
		} finally {
			HibernateSessionFactory.closeSession();
		}
	}

	public Colegio getColegio(Integer coleidn) throws Exception {
		Colegio entity = null;

		try {
			entity = XMLHibernateDaoFactory.getInstance().getColegioDAO()
					.findById(coleidn);
		} catch (Exception e) {
			throw new ZMessManager().new FindingException("Colegio");
		} finally {
		}
		return entity;
	}

	public List<Colegio> getColegioDane(Long coleDane) throws Exception {
		List<Colegio> entity = null;

		try {
			entity = XMLHibernateDaoFactory.getInstance().getColegioDAO()
					.findByColecoddanen(coleDane);
		} catch (Exception e) {
			throw new ZMessManager().new FindingException("Colegio");
		} finally {
		}
		return entity;
	}

	public List<ColegioDTO> getDataColegio() throws Exception {
		try {
			List<Colegio> colegio = XMLHibernateDaoFactory.getInstance()
					.getColegioDAO().findAll();

			List<ColegioDTO> colegioDTO = new ArrayList<ColegioDTO>();

			for (Colegio colegioTmp : colegio) {
				ColegioDTO colegioDTO2 = new ColegioDTO();

				colegioDTO2.setColeidn(colegioTmp.getColeidn());
				colegioDTO2
						.setColecoddanen((colegioTmp.getColecoddanen() != null) ? colegioTmp
								.getColecoddanen() : null);
				colegioDTO2
						.setColedescripv((colegioTmp.getColedescripv() != null) ? colegioTmp
								.getColedescripv() : null);
				colegioDTO2
						.setColedireccionv((colegioTmp.getColedireccionv() != null) ? colegioTmp
								.getColedireccionv() : null);
				colegioDTO2
						.setColeemailv((colegioTmp.getColeemailv() != null) ? colegioTmp
								.getColeemailv() : null);
				colegioDTO2
						.setColefaxv((colegioTmp.getColefaxv() != null) ? colegioTmp
								.getColefaxv() : null);
				colegioDTO2
						.setColelogov((colegioTmp.getColelogov() != null) ? colegioTmp
								.getColelogov() : null);
				colegioDTO2
						.setColesectorv((colegioTmp.getColesectorv() != null) ? colegioTmp
								.getColesectorv() : null);
				colegioDTO2
						.setColetelefonofv((colegioTmp.getColetelefonofv() != null) ? colegioTmp
								.getColetelefonofv() : null);
				colegioDTO2
						.setColezonav((colegioTmp.getColezonav() != null) ? colegioTmp
								.getColezonav() : null);
				colegioDTO2
						.setLugaidn((colegioTmp.getLugaidn() != null) ? colegioTmp
								.getLugaidn() : null);

				if (colegioTmp.getComunidad() != null) {
					colegioDTO2.setComuidn_Comunidad(colegioTmp.getComunidad()
							.getComuidn());
				} else {
					colegioDTO2.setComuidn_Comunidad(null);
				}
				colegioDTO.add(colegioDTO2);
			}

			return colegioDTO;
		} catch (Exception e) {
			throw e;
		}
	}

	public List<Colegio> findPageColegio(String sortColumnName,
			boolean sortAscending, int startRow, int maxResults)
			throws Exception {
		List<Colegio> entity = null;

		try {
			entity = XMLHibernateDaoFactory
					.getInstance()
					.getColegioDAO()
					.findPageColegio(sortColumnName, sortAscending, startRow,
							maxResults);
		} catch (Exception e) {
			throw new ZMessManager().new FindingException("Colegio");
		} finally {
		}

		return entity;
	}

	public Long findTotalNumberColegio() throws Exception {
		Long entity = null;

		try {
			entity = XMLHibernateDaoFactory.getInstance().getColegioDAO()
					.findTotalNumberColegio();
		} catch (Exception e) {
			throw new ZMessManager().new FindingException("Colegio Count");
		} finally {
		}

		return entity;
	}

	/**
	 * 
	 * @param varibles
	 *            este arreglo debera tener:
	 * 
	 *            [0] = String variable = (String) varibles[i]; representa como
	 *            se llama la variable en el pojo
	 * 
	 *            [1] = Boolean booVariable = (Boolean) varibles[i + 1];
	 *            representa si el valor necesita o no ''(comillas simples)usado
	 *            para campos de tipo string
	 * 
	 *            [2] = Object value = varibles[i + 2]; representa el valor que
	 *            se va a buscar en la BD
	 * 
	 *            [3] = String comparator = (String) varibles[i + 3]; representa
	 *            que tipo de busqueda voy a hacer.., ejemplo: where
	 *            nombre=william o where nombre<>william, en este campo iria el
	 *            tipo de comparador que quiero si es = o <>
	 * 
	 *            Se itera de 4 en 4..., entonces 4 registros del arreglo
	 *            representan 1 busqueda en un campo, si se ponen mas pues el
	 *            continuara buscando en lo que se le ingresen en los otros 4
	 * 
	 * 
	 * @param variablesBetween
	 * 
	 *            la diferencia son estas dos posiciones
	 * 
	 *            [0] = String variable = (String) varibles[j]; la variable ne
	 *            la BD que va a ser buscada en un rango
	 * 
	 *            [1] = Object value = varibles[j + 1]; valor 1 para buscar en
	 *            un rango
	 * 
	 *            [2] = Object value2 = varibles[j + 2]; valor 2 para buscar en
	 *            un rango ejempolo: a > 1 and a < 5 --> 1 seria value y 5 seria
	 *            value2
	 * 
	 *            [3] = String comparator1 = (String) varibles[j + 3];
	 *            comparador 1 ejemplo: a comparator1 1 and a < 5
	 * 
	 *            [4] = String comparator2 = (String) varibles[j + 4];
	 *            comparador 2 ejemplo: a comparador1>1 and a comparador2<5 (el
	 *            original: a > 1 and a < 5) *
	 * @param variablesBetweenDates
	 *            (en este caso solo para mysql) [0] = String variable =
	 *            (String) varibles[k]; el nombre de la variable que hace
	 *            referencia a una fecha
	 * 
	 *            [1] = Object object1 = varibles[k + 2]; fecha 1 a
	 *            comparar(deben ser dates)
	 * 
	 *            [2] = Object object2 = varibles[k + 3]; fecha 2 a
	 *            comparar(deben ser dates)
	 * 
	 *            esto hace un between entre las dos fechas.
	 * 
	 * @return lista con los objetos que se necesiten
	 * @throws Exception
	 */
	public List<Colegio> findByCriteria(Object[] variables,
			Object[] variablesBetween, Object[] variablesBetweenDates)
			throws Exception {
		List<Colegio> list = new ArrayList<Colegio>();
		String where = new String();
		String tempWhere = new String();

		if (variables != null) {
			for (int i = 0; i < variables.length; i++) {
				if ((variables[i] != null) && (variables[i + 1] != null)
						&& (variables[i + 2] != null)
						&& (variables[i + 3] != null)) {
					String variable = (String) variables[i];
					Boolean booVariable = (Boolean) variables[i + 1];
					Object value = variables[i + 2];
					String comparator = (String) variables[i + 3];

					if (booVariable.booleanValue()) {
						tempWhere = (tempWhere.length() == 0) ? ("(model."
								+ variable + " " + comparator + " \'" + value + "\' )")
								: (tempWhere + " AND (model." + variable + " "
										+ comparator + " \'" + value + "\' )");
					} else {
						tempWhere = (tempWhere.length() == 0) ? ("(model."
								+ variable + " " + comparator + " " + value + " )")
								: (tempWhere + " AND (model." + variable + " "
										+ comparator + " " + value + " )");
					}
				}

				i = i + 3;
			}
		}

		if (variablesBetween != null) {
			for (int j = 0; j < variablesBetween.length; j++) {
				if ((variablesBetween[j] != null)
						&& (variablesBetween[j + 1] != null)
						&& (variablesBetween[j + 2] != null)
						&& (variablesBetween[j + 3] != null)
						&& (variablesBetween[j + 4] != null)) {
					String variable = (String) variablesBetween[j];
					Object value = variablesBetween[j + 1];
					Object value2 = variablesBetween[j + 2];
					String comparator1 = (String) variablesBetween[j + 3];
					String comparator2 = (String) variablesBetween[j + 4];
					tempWhere = (tempWhere.length() == 0) ? ("(" + value + " "
							+ comparator1 + " " + variable + " and " + variable
							+ " " + comparator2 + " " + value2 + " )")
							: (tempWhere + " AND (" + value + " " + comparator1
									+ " " + variable + " and " + variable + " "
									+ comparator2 + " " + value2 + " )");
				}

				j = j + 4;
			}
		}

		if (variablesBetweenDates != null) {
			for (int k = 0; k < variablesBetweenDates.length; k++) {
				if ((variablesBetweenDates[k] != null)
						&& (variablesBetweenDates[k + 1] != null)
						&& (variablesBetweenDates[k + 2] != null)) {
					String variable = (String) variablesBetweenDates[k];
					Object object1 = variablesBetweenDates[k + 1];
					Object object2 = variablesBetweenDates[k + 2];
					String value = null;
					String value2 = null;

					try {
						Date date1 = (Date) object1;
						Date date2 = (Date) object2;
						value = Utilities
								.formatDateWithoutTimeInAStringForBetweenWhere(date1);
						value2 = Utilities
								.formatDateWithoutTimeInAStringForBetweenWhere(date2);
					} catch (Exception e) {
						list = null;
						throw e;
					}

					tempWhere = (tempWhere.length() == 0) ? ("(model."
							+ variable + " between \'" + value + "\' and \'"
							+ value2 + "\')") : (tempWhere + " AND (model."
							+ variable + " between \'" + value + "\' and \'"
							+ value2 + "\')");
				}

				k = k + 2;
			}
		}

		if (tempWhere.length() == 0) {
			where = null;
		} else {
			where = "(" + tempWhere + ")";
		}

		try {
			list = XMLHibernateDaoFactory.getInstance().getColegioDAO()
					.findByCriteria(where);
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		} finally {
		}

		return list;
	}
	
	  
	  public List<Colegio> encontrarColegios(int startingAt, int maxPerPage, String order, String sortField, Map<String, String> filters, String lugaidn)
			throws Exception {
		List<Colegio> entity = null;
		
		try {
			entity = XMLHibernateDaoFactory
					.getInstance()
					.getColegioDAO()
					.encontrarColegios(startingAt, maxPerPage, order, sortField, filters, lugaidn);
			
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		} finally {
		}
		return entity;
	  }
	  
		public Long findTotalNumberColegio(Map<String, String> filters, String lugaidn) throws Exception {
			Long entity = null;

			try {
				entity = XMLHibernateDaoFactory.getInstance().getColegioDAO()
						.findTotalNumberColegio(filters, lugaidn);
			} catch (Exception e) {
				throw new ZMessManager().new FindingException("Colegio Count");
			} finally {
			}
			return entity;
		}
	  
	  
	  public List<ColegioDTO> getColegioDTO() throws Exception {
			List<ColegioDTO> list = new ArrayList<ColegioDTO>();

			try {
				list = XMLHibernateDaoFactory.getInstance().getColegioDAO()
						.findAllColegioDTO();
			} catch (Exception e) {
				throw new ZMessManager().new GettingException(ZMessManager.ALL
						+ "Colegio");
			} finally {
			}

			return list;
		}
	  
	  }	  
